package com.setup.trac.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.setup.trac.pojo.Allegati;
import com.setup.trac.pojo.Progetti;
import com.setup.trac.pojo.condition.AllegatiFinderByIdAllegato;
import com.setup.trac.pojo.condition.AllegatiFinderBySessioneUtenteWeb;
import com.setup.trac.service.CommonService;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.SQLCondition;
import com.setup.trac.web.form.TicketForm;

public class RimuoviAllegatoController extends ManageTicketController {

	private CommonService commonService;
	private SearchService searchService;

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		String idAllegato = request.getParameter("idAllegato");
		SQLCondition sqlCondition = new AllegatiFinderByIdAllegato(idAllegato);
		Allegati[] allegati = searchService.find(new Allegati[0], sqlCondition,
				Allegati.class);
		if(allegati!=null && allegati.length>0){
			commonService.delete(allegati[0]);
		}
		allegati = getSearchService().find(
				new Allegati[0],
				new AllegatiFinderBySessioneUtenteWeb(request.getSession(false)
						.getId()), Allegati.class);

		ModelAndView mav = new ModelAndView(getSuccessView());
		TicketForm tf = (TicketForm) command;
		Progetti progetti = searchService.findProgettoById(request
				.getParameter("idProgetto"));
		tf.setDescrizioneProgetto(progetti.getDescrizione());
		tf.setIdProgetto(progetti.getIdProgetto().toPlainString());
		mav.addObject("ticket", command);
		mav.addObject("allegati", allegati);
		return mav;
	}

	public CommonService getCommonService() {
		return commonService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}


}
